<template>
    <view class="body">
        <view class="header">
            <view class="userinfo">
                <view style="width: 80px">
                    <image v-if="userInfo?.openId && userInfo?.avatarUrl" class="avatar" :src="userInfo.avatarUrl"> </image>
                    <image v-else class="avatar" src="../../static/images/avatar.png"></image>
                </view>
                <view style="flex: 1">
                    <view class="info">
                        {{ staffInfo?.orName }}
                        <view style="font-size: 11px; font-weight: normal; margin-top: 5px">{{ staffInfo.orPhon }} </view>
                    </view>
                </view>
                <view style="width: 30px">
                    <uni-icons type="scan" size="26" style="margin-right: 20px" @click="scanCode"></uni-icons>
                </view>
            </view>

            <view class="vip">
                <uni-row>
                    <uni-col span="12" class="item">
                        <view class="num">{{ numberFormat(totalPrice, 0) }}</view>
                        <view class="label">成交金额</view>
                    </uni-col>
                    <uni-col span="12" class="item">
                        <view class="num">{{ totalFission }}</view>
                        <view class="label">已裂变客户</view>
                    </uni-col>
                </uni-row>
            </view>
        </view>

        <view style="height: 10px"></view>

        <uni-section title="客户" type="line" padding="0" style="background-color: transparent">
            <uni-grid :column="2" :highlight="true" :showBorder="false" :square="false">
                <uni-grid-item>
                    <view class="grid-box">
                        <view style="display: flex; justify-content: space-between" @click="gotoPage(`/pages/staff/my_customer`)">
                            <view style="flex: 1.5; margin-right: 20; text-align: left">
                                <Text style="color: #9a7d76">我的客户</Text>
                                <view style="font-weight: 600; font-size: 25px; margin-top: 5">{{ totalCustomers }} </view>
                            </view>
                            <view style="margin-top: 10px; margin-left: 0px; text-align: right">
                                <image src="../../static/images/customers.png" mode="aspectFit" style="width: 40px; height: 40px"></image>
                            </view>
                        </view>
                    </view>
                </uni-grid-item>
                <uni-grid-item>
                    <view class="grid-box grid-box1">
                        <view style="display: flex; justify-content: space-between" @click="gotoPage(`/pages/staff/customer_book`)">
                            <view style="flex: 1.5; margin-right: 20; text-align: left">
                                <Text style="color: #9a7d76">客户预约</Text>
                                <view style="font-weight: 600; font-size: 25px; margin-top: 5">{{ totalAppointment }} </view>
                            </view>
                            <view style="margin-top: 10px; margin-left: 0px; text-align: right">
                                <image src="../../static/images/discount.png" mode="aspectFit" style="width: 40px; height: 40px"></image>
                            </view>
                        </view>
                    </view>
                </uni-grid-item>
                <uni-grid-item>
                    <view class="grid-box">
                        <view style="display: flex; justify-content: space-between" @click="gotoPage(`/pages/staff/customer_order`)">
                            <view style="flex: 1.5; margin-right: 20; text-align: left">
                                <Text style="color: #9a7d76">客户订单</Text>
                                <view style="font-weight: 600; font-size: 25px; margin-top: 5px">{{ totalOrder }}</view>
                            </view>
                            <view style="margin-top: 10px; margin-left: 0px; text-align: right">
                                <image src="../../static/images/order.png" mode="aspectFit" style="width: 40px; height: 40px"></image>
                            </view>
                        </view>
                    </view>
                </uni-grid-item>
                <uni-grid-item>
                    <view class="grid-box grid-box1">
                        <view style="display: flex; justify-content: space-between" @click="gotoPage(`/pages/staff/customer_group`)">
                            <view style="flex: 1.5; margin-right: 20; text-align: left">
                                <Text style="color: #9a7d76">客户的团</Text>
                                <view style="font-weight: 600; font-size: 25px; margin-top: 5px">{{ totalGroup }}</view>
                            </view>
                            <view style="margin-top: 10px; margin-left: 0px; text-align: right">
                                <image src="../../static/images/group.png" mode="aspectFit" style="width: 40px; height: 40px"></image>
                            </view>
                        </view>
                    </view>
                </uni-grid-item>
            </uni-grid>
        </uni-section>

        <uni-section title="榜单" type="line" padding="0">
            <uni-grid :column="2" :highlight="true" :showBorder="false" :square="false">
                <uni-grid-item v-for="(item, index) in topLists">
                    <view :class="'grid-box' + (index % 2 === 1 ? ' grid-box1' : '')" @click="gotoPage(item.url)">
                        <view style="display: flex; justify-content: space-between">
                            <view style="margin-top: 8px; margin-left: 0px; text-align: center">
                                <image :src="item.src" mode="aspectFit" style="width: 40px; height: 40px"></image>
                            </view>
                            <view style="flex: 1.5; margin-top: 16px; text-align: center">
                                <view>{{ item.title }}</view>
                            </view>
                        </view>
                    </view>
                </uni-grid-item>
            </uni-grid>
        </uni-section>

        <view style="padding: 10px">
            <view class="list-box">
                <uni-list :border="false">
                    <uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconHome" title="活动首页" rightText="查看" link="switchTab" to="/pages/home/index" />
                    <uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconStaff" title="客户首页" rightText="查看" link="switchTab" to="/pages/ucenter/index" />
                    <uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconStaff" title="我接待的" rightText="查看" link="navigateTo" to="/pages/staff/i_responsible" />
                    <uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconStaff" title="我服务的" rightText="查看" link="navigateTo" to="/pages/staff/i_served" />
                    <uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconStaff" title="小程序码" @click="getWxCode" :clickable="true" />
                </uni-list>
            </view>
        </view>

        <!--        <view style="padding: 20px 10px">
            <u-button type="success" @click="exitLogin">退出登录</u-button>
        </view> -->
        
        <u-modal :show="isOpened" confirmText="保存到相册" cancelText="关闭显示" showCancelButton="true" width="250" @confirm="saveImg()" @cancel="isOpened = false">
        	<image class="avatar" style="width: 200px; height: 200px" :src="filePath"></image>
        </u-modal>
    </view>
</template>

<script>
import { mapMutations, mapGetters } from "vuex";
import { getStaffHomePage, getCustomerServiceItemList, getCustomers, createCustomerServiceItemList, getWxCode } from "../../utils/api";
import { numberFormat, userAuthorization } from "../../utils/helper";
import { validate } from 'uuid';

export default {
    data() {
        return {
            redbag: 0,
            finishOrder: 0,
            order: 0,
            totalAppointment: 0,
            totalCustomers: 0,
            totalOrder: 0,
            totalGroup: 0,
            isOpened: false,
            shareInfo: {},
            totalPrice: 0,
            totalFission: 0,
            topLists: [
                {
                    title: "员工榜单",
                    src: "../../static/images/personrank.png",
                    url: "/pages/staff/staff_rank",
                },
                {
                    title: "超级客户",
                    src: "../../static/images/supermarket.png",
                    url: "/pages/staff/customer_rank",
                },
                {
                    title: "热销项目",
                    src: "../../static/images/hot.png",
                    url: "/pages/staff/item_rank",
                },
                {
                    title: "门店榜单",
                    src: "../../static/images/hero.png",
                    url: "/pages/staff/stores_rank",
                },
            ],
            iconHome: {
                color: "#6699ff",
                size: "22",
                type: "home-filled",
            },
            iconStaff: {
                color: "#6699ff",
                size: "22",
                type: "person-filled",
            },
        };
    },

    onLoad() {
        this.getStaffHomePage();
    },

    onShow() {
        this.getStaffHomePage();
    },

    computed: {
        ...mapGetters({
            appid: "globalInfo/appid",
            userInfo: "personInfo/userInfo",
            staffInfo: "personInfo/staffInfo",
            activity: "activityInfo/activity",
        }),
    },

    watch: {
        staffInfo: {
            handler(newValue, oldValue) {
                if (newValue?.orUuid) {
                    this.getStaffHomePage();
                }
            },
            immediate: true,
            deep: true,
        },
        activity: {
            handler(newValue, oldValue) {
                if (newValue?.gpUuid) {
                    this.getStaffHomePage();
                }
            },
            immediate: true,
            deep: true,
        },
    },
    methods: {
        ...mapMutations({}),

        gotoPage(url) {
            uni.navigateTo({
                url,
            });
        },

        async getStaffHomePage() {
            if (this.staffInfo.orUuid && this.activity.gpUuid) {
                let res = await getStaffHomePage({
                    orUuid: this.staffInfo.orUuid,
                    gpUuid: this.activity.gpUuid,
                });
                let soCuids = res?.orders?.filter((item) => item.soStat === "已支付" && item.soNewc === true);
                let lb = soCuids?.map((_item) => _item.customer?.ciUuid);
                this.totalFission = Array.from(new Set(lb)).length;

                this.totalOrder = res?.orders?.length || 0;
                this.totalCustomers = res?.customersCount || 0;
                this.totalAppointment = res?.appointmentCount || 0;
                this.totalGroup = res?.groupCount || 0;
                let tPrice = 0;
                res?.orders?.forEach((item) => {
                    if (item.soStat === "已支付") tPrice += Number(item.soPric);
                });
                this.totalPrice = tPrice;
            }
        },

        exitLogin() {
            const that = this;
            uni.showModal({
                title: "确认要退出当前务联登录吗？",
                success: async (res) => {
                    if (res.confirm) {
                        that.$store.dispatch("personInfo/save", {
                            staffInfo: {},
                        });
                        uni.switchTab({
                            url: "/pages/ucenter/index",
                        });
                    }
                },
            });
        },
        
        scanCode() {
            const that = this;
            uni.scanCode({
                onlyFromCamera: true,
                scanType: ["qrCode"],
                success: async function (res) {
                    //检查是否是UUID如果不是则返回“无效的客户码” 
                    if(!validate(res.result)){
                       return uni.showToast({ title: "无效的客户码", icon: "error", duration: 2000 });
                    }
                    //检查该UUID是否是客户的UUID如果不是则返回“无效的客户码”
                    let resCust = await getCustomers({ ciUuid: res.result });

                    if (resCust?.length < 1) {
                        return uni.showToast({ title: "没有您的用户信息", icon: "error", duration: 2000 });
                    }
                    //查询客户是否有未完成的客户清单
                    let resList = await getCustomerServiceItemList({ ciUuid: res.result, crStat: "待确认" });
                    if (resList?.length < 1) {
                        //创建客户服务清单,并渠道该服务清单详情页
                        let saveData = {
                            ciUuid: resCust[0].ciUuid,
                            ciName: resCust[0].ciName || resCust[0].ciAlia,
                            ciPhon: resCust[0].ciPhon,
                            crCrti: new Date().getUTCTime(),
                            crRsid: that.staffInfo.orUuid,
                            crRsna: that.staffInfo.orName,
                            crRsph: that.staffInfo.orPhon,
                            crStat: "待确认",
                            osUuid: that.staffInfo.store.osUuid,
                        };
                        let resCreate = await createCustomerServiceItemList(saveData);
                        if (resCreate)
                            uni.navigateTo({
                                url: `/pages/staff/customer_current_service_item?ciUuid=${res.result}`,
                            });
                    }
                    if (resList?.length === 1 || resList?.length > 1) {
                        //直接去到该服务清单详情页
                        uni.navigateTo({
                            url: `/pages/staff/customer_current_service_item?ciUuid=${res.result}`,
                        });
                    }
                },
            });
        },
        
        async getWxCode() {
        	const fs = uni.getFileSystemManager();
        	const filePath = `${wx.env.USER_DATA_PATH}/888.png`;
        	try {
        		fs.accessSync(filePath);
        	} catch (e) {
        		let res = await getWxCode({
        			appid: this.appid,
        			page: "pages/staff/login",
        			scene: "staff",
        		});
        		if (res) {
        			// 将返回的图片buffer生成图片，并保存至临时用户文件中
        			fs.writeFileSync(filePath, res, "base64");
        		}
        	}
        	this.filePath = filePath;
        	this.isOpened = true;
        },
        
        saveImg() {
        	uni.saveImageToPhotosAlbum({
        		filePath: this.filePath,
        		success: (res) => {
        			uni.showToast({
        				title: "已保存到相册",
        				icon: "success",
        				duration: 3000,
        			});
        		},
        		fail: async (err) => {
        			if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
        				const ret = await uni.getSetting();
        				if (ret.authSetting["scope.writePhotosAlbum"]) {
        					uni.showToast({
        						title: "已授权",
        						icon: "success",
        					});
        				}
        				if (ret.authSetting["scope.writePhotosAlbum"] == false) {
        					uni.showModal({
        						title: "提示",
        						content: "图片保存失败，请前往设置页面允许保存相册",
        						confirmColor: "#8C5CDD",
        						success: function (res) {
        							if (res.confirm) {
        								uni.openSetting({
        									success(res) {
        										console.log(res);
        									},
        								});
        							}
        							if (res.cancel) {
        								uni.showToast({
        									title: "取消",
        									icon: "error",
        								});
        							}
        						},
        					});
        				}
        			}
        		},
        	});
        },
    },
};
</script>

<style lang="scss" scoped>
page {
    margin-bottom: 10px;
}

.header {
    padding: 80px 10px 0 10px;
    background-color: #ba8d76;

    .userinfo {
        display: flex;
        padding: 10px 15px 10px 24px;
        background-color: #fff;
        border-radius: 5px;
        margin-top: 20px;
    }

    .avatar {
        height: 60px;
        width: 60px;
        border-radius: 50%;
    }

    .info {
        font-weight: 600;
        font-size: 14px;
        margin-top: 10px;
    }

    .vip {
        color: #fff;
        padding: 20px 0;

        .num {
            margin-top: 5px;
            text-align: center;
            font-size: 20px;
        }

        .label {
            text-align: center;
            font-size: 12px;
            margin-top: 5px;
        }
    }
}

.list-box {
    padding: 2px;
    border-radius: 6px;
    box-shadow: 0 0px 6px 1px rgba(165, 165, 165, 0.2);
    background-color: #fff;
    margin-bottom: 10px;
}

.grid-box {
    border-radius: 10px;
    box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.2);
    background-color: #eee;
    padding: 10px 20px;
    margin: 0 5px 10px 10px;
}

.grid-box1 {
    margin: 0 10px 5px 5px;
}
</style>
